package cn.com.pc.content.converter;

import org.springframework.core.convert.converter.Converter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * Spring MVC LocalDateTime转换
 */
public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {
    private static final List<String> formarts = new ArrayList<>(4);
    static{
        formarts.add("yyyy-MM-dd HH:mm:ss");
        formarts.add("yyyy/MM/dd HH:mm:ss");
    }

    @Override
    public LocalDateTime convert(String source) {
        String value = source.trim();
        if ("".equals(value)) {
            return null;
        }
        if(source.matches("^\\d{4}-\\d{1,2}$")){
            return LocalDateTime.parse(source + "-01 00:00:00", DateTimeFormatter.ofPattern(formarts.get(0)));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")){
            return LocalDateTime.parse(source + " 00:00:00", DateTimeFormatter.ofPattern(formarts.get(0)));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
            return LocalDateTime.parse(source + ":00", DateTimeFormatter.ofPattern(formarts.get(0)));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
            return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(formarts.get(0)));
        }else if(source.matches("^\\d{4}/\\d{1,2}$")){
            return LocalDateTime.parse(source + "-01 00:00:00", DateTimeFormatter.ofPattern(formarts.get(1)));
        }else if(source.matches("^\\d{4}/\\d{1,2}/\\d{1,2}$")){
            return LocalDateTime.parse(source + " 00:00:00", DateTimeFormatter.ofPattern(formarts.get(1)));
        }else if(source.matches("^\\d{4}/\\d{1,2}/\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
            return LocalDateTime.parse(source + ":00", DateTimeFormatter.ofPattern(formarts.get(1)));
        }else if(source.matches("^\\d{4}/\\d{1,2}/\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
            return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(formarts.get(1)));
        }else{
            throw new IllegalArgumentException("Invalid LocalDateTime value '" + source + "'");
        }
    }
}
